package com.chinawayltd.ews.sample.web.basicInfo;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.model.TLimiter;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.service.basicInfo.LimiterService;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.util.BaseController;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelGenerateModel;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExcelUtils;
import com.chinawayltd.ews.sample.web.query.LimiterGirdQuery;
import com.chinawayltd.ews.sample.web.query.LogGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 道路限行管理
 * @author: chenxin
 * @create: 2018年4月11日 下午11:12:23
 */
@Api(tags = { "道路限行管理API" })
@RestController
@RequestMapping(value = "/web/limiter")
public class LimiterController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	LimiterService limiterService;
    @Autowired
    private CommonService commonService;
	private final String tableName = "T_LIMITER";
	
	@ApiOperation(value = "列表查询接口")
	@RequestMapping(value = "/loadGirdData", method = { RequestMethod.POST })
	public ResultModel loadGirdData(LimiterGirdQuery queryParam) {
		ResultModel model = new ResultModel();
		try {
			List<TLimiter> list = limiterService.list(queryParam);
			model.setCode(0);
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", list));
			model.setPage(queryParam);
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", null));
			logger.error("道路限行管理列表查询出错！", e);
		}
		return model;
	}

	@ApiOperation(value = "道路限行管理信息根据ID查询接口")
	@RequestMapping(value = "/find/{id}", method = { RequestMethod.GET })
	@ApiImplicitParam(paramType = "path", name = "id", value = "道路限行管理ID", dataType = "Long", required = true)
	public ResultModel getById(@PathVariable Long id) {
		ResultModel model = new ResultModel();
		try {
			TLimiter data = limiterService.getById(id);
			model.setData(new JSONObject().fluentPut("result", data));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", null));
			logger.error("路限行管理信息根据ID查询出错！id：" + id, e);
		}
        return model;
	}

	@ApiOperation(value = "道路限行管理信息新增接口")
	@RequestMapping(value = "/add", method = { RequestMethod.POST })
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType="query", name="limiterName",value="限行条件名称",dataType="String",required=true),
    	@ApiImplicitParam(paramType="query", name="bigLimiterTime",value="限行开始时间",dataType="String",required=true),
    	@ApiImplicitParam(paramType="query", name="endLimiterTime",value="限行结束时间",dataType="String",required=true)
    })
	public ResultModel add(TLimiter tLimiter) {
		ResultModel model = new ResultModel();
		try {
			if(StringUtils.isBlank(tLimiter.getLimiterName())){
				throw new RuntimeException("添加失败！");
			}
			List<TLimiter> list = limiterService.getLimiterByNameAndId(null, tLimiter.getLimiterName());
			if(list.size() > 0){
				throw new RuntimeException("名称存在，添加失败！");
			}
			int result = limiterService.add(tLimiter);
			if(result > 0){
	        	model.setData(new JSONObject().fluentPut("result" , "添加成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "添加失败"));
	        }
		} catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
        } catch (Exception e) {
			model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg" , "添加失败"));
			logger.error("道路限行管理信息新增发生异常！", e);
		}
        return model;
	}

	@ApiOperation(value = "道路限行管理信息修改接口")
	@RequestMapping(value = "/update", method = { RequestMethod.POST })
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType="query", name="id",value="道路限行id",dataType="Long",required=true),
    	@ApiImplicitParam(paramType="query", name="limiterName",value="限行条件名称",dataType="String",required=true),
    	@ApiImplicitParam(paramType="query", name="bigLimiterTime",value="限行开始时间",dataType="String",required=true),
    	@ApiImplicitParam(paramType="query", name="endLimiterTime",value="限行结束时间",dataType="String",required=true)
    })
	public ResultModel update(TLimiter tLimiter) {
		ResultModel model = new ResultModel();
		try {
			// 不需要校验唯一
			if(StringUtils.isBlank(tLimiter.getId().toString()) || StringUtils.isBlank(tLimiter.getLimiterName())){
				throw new RuntimeException("修改失败！");
			}
			List<TLimiter> list = limiterService.getLimiterByNameAndId(tLimiter.getId(), tLimiter.getLimiterName());
			if(list.size() > 0){
				throw new RuntimeException("修改失败！");
			}
			int result = limiterService.update(tLimiter);
			if(result > 0){
	        	model.setData(new JSONObject().fluentPut("result" , "修改成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "修改失败"));
	        }
		} catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
        } catch (Exception e) {
			model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg" , "修改失败"));
			logger.error("道路限行管理信息修改发生异常！！", e);
		}
        return model;
	}
	
	@ApiOperation(value = "通过限行条件名称查询对象,可用来校验名称唯一性", notes = "校验名称：添加校验名称不需要ID,修改校验名称必要ID,返回Sub_code=0为可用,1为已存在!")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "limiterId", value = "限行id", dataType = "Long", required = false),
		@ApiImplicitParam(paramType = "query", name = "limiterName", value = "限行名称", dataType = "String", required = true)})
	@RequestMapping(value = { "/getLimiterByNameAndId" }, method = RequestMethod.POST)
	public ResultModel getLimiterByNameAndId(Long limiterId, String limiterName){
		ResultModel model = new ResultModel();
		try {
			List<TLimiter> list = limiterService.getLimiterByNameAndId(limiterId, limiterName);
			if(list.size() > 0){
				model.setData(new JSONObject().fluentPut("result" , "已存在"));
			}else{
				model.setData(new JSONObject().fluentPut("result" , "可用"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg" , "查询失败"));
			logger.error("查询失败！", e);
		}
		return model;
	}

	@ApiOperation(value = "道路限行管理信息删除接口")
	@RequestMapping(value = "/delete/{id}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "id", value = "道路限行管理信息ID", dataType = "Long", required = true)
	public ResultModel delete(@PathVariable Long id) {
		ResultModel model = new ResultModel();
        try {
        	int result = limiterService.delete(id);
            if(result > 0){
            	model.setData(new JSONObject().fluentPut("result" , "删除成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
	        }
		} catch (Exception e) {
			model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
			logger.error("道路限行管理信息删除发生异常！id=="+id, e);
		}
		return model;
	}
	
    @ApiOperation(value = "通过ID查询操作日记接口")
    @RequestMapping(value = "/getLogDataById", method = { RequestMethod.POST })
    public ResultModel getLogDataById(LogGirdQuery queryParam) {
		ResultModel model = new ResultModel();
		try {
			queryParam.setTableName(tableName);
            List<TLog> list = commonService.getLogDataById(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", null));
            logger.error("通过ID查询操作日记接口异常！", e);
        }
        return model;
    }
    
	@ApiOperation(value = "批量删除接口")
	@RequestMapping(value = "/deleteAll/{ids}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "ids", value = "拼接需要删除的数据id串如：1,2,3,4", dataType = "String", required = true)
	public ResultModel deleteAll(@PathVariable String ids) {
		ResultModel model = new ResultModel();
		try {
			String[] idArr = ids.split(",");
			int result = limiterService.deletesByIds(idArr);
            if(result > 0){
            	model.setData(new JSONObject().fluentPut("result" , "删除成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
	        }
		} catch (Exception e) {
			model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
		}
		return model;
	}
	
	@ApiOperation(value = "道路限行管理导出接口")
    @RequestMapping(value = "/exportGirdData", method = { RequestMethod.POST })
    public void exportGirdData(@RequestBody LimiterGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
            List<TLimiter> branchList = limiterService.list(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(branchList)
                    .cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "道路限行管理列表" , request, response);
        }catch (Exception e){
            logger.error("道路限行管理列表导出出错！", e);
        }
    }
	
	/**解析excel2003和2007的数据，并导入到数据库，错误数据导出到前台
	 * @author Fay
	 * @date 2018年5月3日 上午10:07:15
	 * @param file
	 * @param request
	 * @param response
	 */
	@ApiOperation(value = "道路限行信息批量导入")
	@SuppressWarnings("rawtypes")
	@RequestMapping(value="/readExcel", method = { RequestMethod.POST })
	public Object readExcel(@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
		JSONObject object = new JSONObject();
		try {
    		// 1、解析导入的数据
	    	ExcelObjModel model = ExcelUtils.readExcel(file);
	    	if(model.getCode() !=0){
	    		object.put("state", 400);
		    	object.put("msg", model.getMsg());
				return object.toString();
			}
			// 2、导入数据到数据库
			List<PageData> list = (List)model.getList();
			if(list ==null || list.isEmpty()){
				object.put("state", 400);
		    	object.put("msg", "导入的表不是有效的文件或数据为空");
		    	return object.toString();
			}
			ExcelObjModel result = limiterService.insertList(list);
			// 3、导出错误数据
			if(result.getList().size() >0){
		        ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(result.getList()).cloumnList(result.getCloums()).build();
		        Workbook workbook = ExcelUtils.generateExcel(excelModel);
				this.sendWorkbook(workbook, "道路限行信息" , request, response);
			}
    	} catch (BusinessException e) {
		 	object.put("state", 400);
	    	object.put("msg", e.getMessage());
	    	return object.toString();
		} catch (IOException e) {
			object.put("state", 400);
	    	object.put("msg", "导入数据接口出错");
	    	return object.toString();
		} catch (Exception e) {
			logger.error("导入数据接口出错！", e);
		}
    	return null;
    }
}
